<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/7/7 9:39
 * Desc:
 */

namespace App\Service;


use App\Models\CategoryVersion;

class CategoryVersionService extends BaseService
{
    protected $modelName = "CategoryVersion";

    /**
     * 插入多条数据
     */
    public function insertAndUpdate($id,$data){
        //获取数据
        $data = $this->getCVData($id,$data);
        $categoryVersion = new CategoryVersion();
        if(is_array($data)){
            //添加更新
            foreach ($data["data"] as $k=>$v){
                $where = ["category_id"=>$v["category_id"],"version_id"=>$v["version_id"]];
                $has = $categoryVersion->whereBuilder($where)->get()->toArray();
                if(empty($has)){
                    $this->create($data["data"][$k]);
                    $msg = "科目[".$v["category_id"]."]版本添加成功";
                }else{
                    $categoryVersion->whereBuilder($where)->update(["usable"=>$v["usable"],"default"=>$v["default"]]);
                    $msg = "科目[".$v["category_id"]."]版本更新成功";
                }
            }
            //删除
            foreach ($data["del"] as $kd=>$vd){
                $this->delete($data["del"][$kd]);
            }
            return ["error"=>0,"msg"=>$msg];
        }
        return ["error"=>80004,"msg"=>""];
    }

    /**
     * 获取添加数据
     */
    private function getCVData($id,$data){
        $arr = [];
        //更新添加的而数据
        foreach ($data["version_id"] as $k=>$v){
            $arr[$k]["category_id"]=$id;
            $arr[$k]["version_id"]=$v;
            $arr[$k]["usable"]=$data["usable"][$k];
            $arr[$k]["default"]=$data["default"][$k];
        }
        //删除的数据
        $del=[];
        if(array_key_exists("del",$data)){
            foreach ($data["del"] as $kd=>$kv){
                $temp = explode("|",$kv);
                $del[$kd]["category_id"]=$temp[0];
                $del[$kd]["version_id"]=$temp[1];
            }
        };
        return ["data"=>$arr,"del"=>$del];
    }

}
